import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { setTime, getTime } from '@/utils/auth'
import router from '@/router'
// 创建axios
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})
// 主动注入时间戳token
const setTimeout = () => {
  return (Date.now() - getTime()) / 1000 > 5000
}
// 请求拦截器
service.interceptors.request.use(config => {
  if (store.state.user.token && !config.headers.Authorization) {
    if (!setTimeout()) {
      config.headers = { Authorization: `Bearer ${store.state.user.token}` }
    } else {
      store.dispatch('user/logout')
      router.push({ path: '/login' })
      return Promise.reject(new Error('登录已过期,请重新登录'))
    }
  }
  setTime()
  return config
}, err => {
  return Promise.reject(err)
})

// 响应拦截器
service.interceptors.response.use(res => {
  const { data, message, success } = res.data
  if (success) {
    return data
  } else {
    Message.error(message)
    return Promise.reject(new Error(message))
  }
}, err => {
  // console.dir(err)
  if (err.response && err.response.data && err.response.data.code === 10002) {
    store.dispatch('user/logout')
    router.push({ path: '/login' })
    Message.error('登录已过期,请重新登录')
  } else {
    Message.error(err.message)
  }
  return Promise.reject(new Error(err))
})
// 暴露出去
export default service
